package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaContants;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Member;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.heima.model.common.dtos.ResponseResult.errorResult;

/**
 * @author feng js
 */
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper,WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String fileUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null) {
            return errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件为空");
        }
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        WmUser user = WmThreadLocalUtils.getUser();
        WmMaterial material = new WmMaterial();
        material.setUserId(user.getId());
        material.setType((short)0);
        material.setIsCollection((short)0);
        material.setCreatedTime(new Date());
        material.setUrl(fileId);
        save(material);
        material.setUrl(fileUrl+fileId);

        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult findWmPicture(WmMaterialDto wmMaterialDto) {
        if (wmMaterialDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        Page<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询对应用户的素材
        if (WmThreadLocalUtils.getUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无法获得Id");
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        //查询收藏的素材
        if (wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection()==1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        //根据创建时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> result = page(page,lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(), (int) result.getTotal());
        List<WmMaterial> records = result.getRecords();
        //拼接图片访问路径
        records = records.stream().map(item -> {
            item.setUrl(fileUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(records);
        return responseResult;
    }
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial material = getById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"图片正在使用");
        }
        fastDFSClient.delFile(material.getUrl().replace("fileServerUrl",""));
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateCollection(Integer id,Short type) {
        if (id == null ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (WmThreadLocalUtils.getUser() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无法获得Id");
        }
        update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId()).set(WmMaterial::getIsCollection,type));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
